package com.lsp.test.concurrentutils;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

public class CyclicBarrierExample {

    static class  Writer extends Thread{
        private CyclicBarrier cyclicBarrier;

        public Writer(CyclicBarrier cyclicBarrier) {
            this.cyclicBarrier = cyclicBarrier;
        }

        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName()+"数据写入完毕，等待其他线程执行！");
                TimeUnit.SECONDS.sleep(1);
                cyclicBarrier.await();  //-1操作
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(4,()->{
            System.out.println("所有数据已经读取完成！开始写入");
        });

        for (int i = 0; i < 4; i++){
            new Writer(cyclicBarrier).start();
        }
    }
}
